package org.example.generics;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public class JsonHandler {

    public void handle() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String jsonInput = "[{\"name\":\"John Doe\"},{\"name\":\"Jane Doe\"}]";

        // 使用 TypeReference 来指定具体的泛型类型
        TypeReference<List<User>> typeRef = new TypeReference<List<User>>() {};

        // 将 JSON 字符串转换为 User 对象列表
        List<User> users = mapper.readValue(jsonInput, typeRef);

        // 输出转换后的对象
        users.forEach(user -> System.out.println(user.getName()));

        TypeReference<List<Map<String,Object>>> typeRef2 = new TypeReference<List<Map<String, Object>>>() {};

        List<Map<String,Object>> maps = mapper.readValue(jsonInput, typeRef2);
        maps.forEach(map-> System.out.println(map));
    }

    public static void main(String[] args) throws JsonProcessingException {
        JsonHandler handler = new JsonHandler();
        handler.handle();
    }
}
